package com.charles.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Data
@EqualsAndHashCode(callSuper = false)
public class EasyExcelListener<T> extends AnalysisEventListener<T> {

    //失败结果集
    //成功结果集
    private List<ExcelValidateDto<T>> successList = new ArrayList<>();

    //失败结果集
    private List<ExcelValidateDto<T>> errorList = new ArrayList<>();

    //excel对象的反射类
    private Class<T> clazz;

    public EasyExcelListener(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        ReadRowHolder readRowHolder = analysisContext.readRowHolder();
        String errMsg;
        try {
            //根据excel数据实体中的javax.validation + 正则表达式来校验excel数据
            errMsg = EasyExcelValidHelper.validateEntity(t);
        } catch (NoSuchFieldException e) {
            errMsg = "解析数据出错";
            e.printStackTrace();
        }
        if (!StrUtil.isEmpty(errMsg)) {
            ExcelValidateDto<T> excelValidateDto = new ExcelValidateDto<>(t, readRowHolder.getRowIndex(), errMsg);
            errorList.add(excelValidateDto);
        } else {
            ExcelValidateDto<T> excelValidateDto = new ExcelValidateDto<>(t, readRowHolder.getRowIndex(), errMsg);
            successList.add(excelValidateDto);
        }
    }

    //所有数据解析完成了 都会来调用
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }


    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        List<String> headValueList = new ArrayList<>(headMap.values());
        if (EasyExcelUtils.validateHead(headValueList, clazz)) {
            return;
        }
        throw new RuntimeException("该模板不符合条件，请检查");

    }


}